<template>
  <div class="main-burialDepthQuery">
    <div class="layui-tab layui-tab-brief" lay-filter="test-handle">
      <ul class="layui-tab-title">
        <li class="layui-this" lay-id="search">查询</li>
        <li lay-id="result">显示结果</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div class="layui-row queryPanel">
            <div class="layui-col-md6">
              <div class="layui-form-item" style="margin-bottom: 0;">
                <label class="layui-form-label">类型:</label>
                <div class="layui-input-block">
                  <select id="maishenSearch_layerSelect" style="width:200px; height:30px; color:black;">
                    <option v-for="(item,index) in typeOptions" :key="index" style="color:#000"
                            :value="item.pipelineType">{{ item.type }}
                    </option>
                  </select>
                </div>
              </div>
              <div class="layui-form-item" style="margin-bottom: 0;">
                <label class="layui-form-label">范围:</label>
                <div class="layui-input-block" style="display:flex; align-items:center;">
                  <select id="conditionSelect1" style="width:100px; height:30px; color:black;">
                    <option style="color:#000" value="0.1">0.1</option>
                    <option style="color:#000" value="0.2">0.2</option>
                    <option style="color:#000" value="0.3">0.3</option>
                    <option style="color:#000" value="0.4">0.4</option>
                    <option style="color:#000" value="0.5">0.5</option>
                    <option style="color:#000" value="0.6">0.6</option>
                    <option style="color:#000" value="0.7">0.7</option>
                    <option style="color:#000" value="0.8">0.8</option>
                    <option style="color:#000" value="0.9">0.9</option>
                    <option style="color:#000" value="1.0">1.0</option>
                    <option style="color:#000" value="2.0">2.0</option>
                    <option style="color:#000" value="3.0">3.0</option>
                    <option style="color:#000" value="4.0">4.0</option>
                    <option style="color:#000" value="5.0">5.0</option>
                    <option style="color:#000" value="6.0">6.0</option>
                    <option style="color:#000" value="12.0">12.0</option>
                  </select>
                  &nbsp;&nbsp;&nbsp;&nbsp; ~ &nbsp;&nbsp;&nbsp;&nbsp;
                  <select id="conditionSelect2" style="width:100px; height:30px; color:black;">
                    <option style="color:#000" value="0.1">0.1</option>
                    <option style="color:#000" value="0.2">0.2</option>
                    <option style="color:#000" value="0.3">0.3</option>
                    <option style="color:#000" value="0.4">0.4</option>
                    <option style="color:#000" value="0.5">0.5</option>
                    <option style="color:#000" value="0.6">0.6</option>
                    <option style="color:#000" value="0.7">0.7</option>
                    <option style="color:#000" value="0.8">0.8</option>
                    <option style="color:#000" value="0.9">0.9</option>
                    <option style="color:#000" value="1.0" selected>1.0</option>
                    <option style="color:#000" value="2.0">2.0</option>
                    <option style="color:#000" value="3.0">3.0</option>
                    <option style="color:#000" value="4.0">4.0</option>
                    <option style="color:#000" value="5.0">5.0</option>
                    <option style="color:#000" value="6.0">6.0</option>
                    <option style="color:#000" value="12.0">12.0</option>
                  </select>
                </div>
              </div>
              <!-- <div class="layui-form-item" style="margin-bottom: 0;">
                  <label class="layui-form-label">管径:</label>
                  <div class="layui-input-block">
                      <input id="maishen_valueInput" type="text" style="width:200px;" placeholder="请输入管径" class="layui-input" lay-affix="number" />
                  </div>
              </div> -->
            </div>
            <div class="layui-col-md12 layui-col-md-offset1">
              <input type="button" class="btn btn-primary" value="矩形" @click="drawRectangle"/>
              <input type="button" class="btn btn-primary" value="面" @click="drawPolygon"/>
              <input type="button" class="btn btn-primary" value="圆" @click="drawCircle"/>
              <input type="button" class="btn btn-primary" value="清除" @click="clearDraw"/>
            </div>
          </div>
        </div>
        <div class="layui-tab-item">
          <table
              id="maishen_table"
              data-toggle="table"
              data-height="550"
              data-width="430"
              data-search="true"
              data-pagination="true"
              style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap; color:#fff;"
          >
            <thead id="maishen_thead" style="color:#fff;">

            </thead>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import layersMap from "@/components/js/layerMap";
import clearWindow from "@/components/js/clearWindow";
import fetchData from "@/components/js/fetchData";
import highLightColor from "@/components/js/highColor";

let $table
// eslint-disable-next-line no-unused-vars
let from
export default {
  name: "burialDepthQuery",
  components: {},
  data() {
    return {
      typeOptions: []
    };
  },
  mounted() {
    $table && $table.bootstrapTable('destroy')
    $table = null;
    clearWindow()
    layersMap.forEach(item => {
      this.typeOptions.push({
        pipelineType: item.pipelineType,
        type: item.type
      })
    })
  },
  methods: {
    allowHandleSearch() {
      let pipeline = $('#maishenSearch_layerSelect').val()
      let condition1 = $('#conditionSelect1').val()
      let condition2 = $('#conditionSelect2').val()
      // eslint-disable-next-line no-unused-vars
      let value = $('#maishen_valueInput').val()

      if (!pipeline || !condition1 || !condition2) {
        layui.layer.alert('请选择管线类型、条件！')
        return false;
      }

      if (condition1 > condition2) {
        layui.layer.alert('条件1不能大于条件2！')
        return false;
      }

      return true;
    },
    clearDraw() {
      console.log('---maishenSearchClazz.clearDraw()')
      window.viewer.dadi.draw.clearDraw();
      from = null;
    },
    hideLayerContent() {
      this.$emit('hidden')
    },
    async handleSearch() {
      let drawGeojson = window.viewer.dadi.draw.toGeoJSON()

      // 求from
      if (drawGeojson.features[0].properties.type === 'circle') {
        from = turf.buffer(turf.feature(drawGeojson.features[0].geometry), Number(drawGeojson.features[0].properties.style.radius) / 1000, {units: 'kilometers'})
      } else if (drawGeojson.features[0].properties.type === 'polygon') {
        from = turf.feature(drawGeojson.features[0].geometry)
      } else if (drawGeojson.features[0].properties.type === 'rectangle') {
        let geo = drawGeojson.features[0].geometry.coordinates.reduce(function (a, b) {
          a.splice(-1)
          b.splice(-1)
          return a.concat(b)
        })
        console.log(geo)
        from = turf.bboxPolygon(geo)
      }

      let properties = [];

      let mylayer = layersMap.find(l => l.pipelineType === $('#maishenSearch_layerSelect').val())
      if (mylayer) {
        const r = await fetchData(mylayer.url)
        r.features.forEach(fea => {
          // 空间筛选
          let to = turf.feature(fea.geometry)
          let withIntersect = turf.booleanIntersects(to, from);
          if (withIntersect) {
            let maishen1 = fea.properties['起点埋深']
            let maishen2 = fea.properties['终点埋深']
            let condition1 = $('#conditionSelect1').val()
            let condition2 = $('#conditionSelect2').val()
            if (Math.min(maishen1, maishen2) >= condition1 && Math.max(maishen1, maishen2) <= condition2) {
              properties.push({...fea.properties,})
            }
          }
        })

        if (properties.length === 0) {
          this.$message.warning('没有查询到符合条件的管径！')
          // layui.layer.msg('没有查询到符合条件的管径！')
          return;
        }

        refreshTable(properties, this)
        layui.element.tabChange('test-handle', 'result'); // 切换到：标签3
      }

      function refreshTable(tableArr, that) {
        $table = $('#maishen_table');
        let thead = `<tr>`
        Object.keys(tableArr[0]).forEach(key => {
          thead += `<th data-field="${key}">${key}</th>`
        })
        thead += `</tr>`
        $table.bootstrapTable('destroy')
        $('#maishen_thead').html(thead)
        $table.bootstrapTable({
          data: tableArr,
          // eslint-disable-next-line no-unused-vars
          onClickRow: function (row, $element) {
            that.highLight(row)
          }
        })
        $table.bootstrapTable('refresh')
      }

    },
    showLayerContent() {
      this.$emit('show')
    },
    async highLight(row) {
      let name = row['线型码']
      window.viewer.scene.primitives._primitives.forEach(tileset => {
        if (tileset instanceof Cesium.Cesium3DTileset) {
          tileset.style = new Cesium.Cesium3DTileStyle({
            color: {
              conditions: [
                ["${name} === '" + name + "'", 'color("red", 1)'.replace('red', highLightColor)],
                ['true', 'color("white")']
              ]
            },
          });
        }
      })


      let layer = layersMap.find(l => l.pipelineType == $('#maishenSearch_layerSelect').val())
      const res = await fetchData(layer.url)
      const feature = res.features.find(fea => fea.properties['线型码'] === row['线型码'])
      var highLightLayer = window.viewer.dataSources.getByName('highLightLayer')[0]
      if (!highLightLayer) {
        highLightLayer = new Cesium.CustomDataSource('highLightLayer')
        window.viewer.dataSources.add(highLightLayer)
      }
      // 绘制
      highLightLayer.entities.removeAll()
      feature.geometry.coordinates.forEach(coordinate => {
        highLightLayer.entities.add({
          name: "polyline",
          polyline: {
            show: true, //是否显示，默认显示
            positions: Cesium.Cartesian3.fromDegreesArrayHeights(coordinate.flat()),
            width: 2, //线的宽度（像素），默认为1
            granularity: Cesium.Math.RADIANS_PER_DEGREE,
            material: Cesium.Color.BLUE, //线的颜色，默认为白色
            // depthFailMaterial: Cesium.Color.RED, //线被遮挡部分的颜色，默认为空（不显示被遮挡的部分），设置后可显示被遮挡的部分
            arcType: Cesium.ArcType.NONE, //线的地理类型，NONE表示纯直线，GEODESIC表示为测地线，RHUMB表示等角航线，默认为测地线
            // arcType: Cesium.ArcType.GEODESIC,
            // arcType: Cesium.ArcType.RHUMB,
            clampToGround: false, //是否贴地，默认为否
            shadows: Cesium.ShadowMode.DISABLED, //是否显示光照阴影，默认为否
            // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(100.0, 2000000.0), //显示的视角距离条件，在该范围内显示，范围不显示，默认为空
            classificationType: Cesium.ClassificationType.BOTH,
            zIndex: 0, //显示深度，越大表示图层在上
          }
        })
      })
      window.viewer.flyTo(highLightLayer, {
        offset: new Cesium.HeadingPitchRange(0.0, -3.1415926 / 2.0, 70.0),
      })
    },
    drawPolygon() {
      let flag = this.allowHandleSearch();
      if (!flag) return;
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "polygon",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        // eslint-disable-next-line no-unused-vars
        success: (entity) => {
          this.handleSearch()
          this.showLayerContent()
        }
      });
    },
    drawRectangle() {
      let flag = this.allowHandleSearch();
      if (!flag) return;
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "rectangle",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        // eslint-disable-next-line no-unused-vars
        success: (entity) => {
          this.handleSearch()
          this.showLayerContent()
        }
      });
    },
    drawCircle() {
      let flag = this.allowHandleSearch();
      if (!flag) return;
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "circle",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        // eslint-disable-next-line no-unused-vars
        success: (entity) => {
          this.handleSearch()
          this.showLayerContent()
        }
      });
    },

  },
  watch: {},
  computed: {},
  beforeDestroy() {
    clearWindow()
    this.clearDraw()
    let highLightLayer = window.viewer.dataSources.getByName('highLightLayer')[0]
    if (!highLightLayer) {
      highLightLayer = new Cesium.CustomDataSource('highLightLayer')
      window.viewer.dataSources.add(highLightLayer)
    }
    // 绘制
    highLightLayer.entities.removeAll()
  },
}
</script>

<style scoped>
.main-burialDepthQuery {
  position: relative;
  height: 100%;
  width: 100%;
}

.queryPanel {
  width: 100%;
  height: 150px;
  display: flex;
  flex-direction: column;

}

.queryPanel > div:nth-child(1) {
  padding: 10px 0;
  height: 90px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.queryPanel > div:nth-child(2) {
  margin-left: 50px;
  margin-top: 10px;
}
</style>
